package models

import (
	"time"

	"lottery/libs/mymgo"
	"lottery/utils"

	//"github.com/astaxie/beego/logs"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

const (
	ORDER_COL_STR = "order"
)

// 订单
type Order struct {
	Id       int64 `json:"id" bson:"_id"`            // 订单ID
	UserId   int64 `json:"userId" bson:"userId"`     // 用户ID
	PolicyId int64 `json:"policyId" bson:"policyId"` // 策略ID
	HScore   int   `json:"hscore" bson:"hscore"`     // 主队得分
	AScore   int   `json:"ascore" bson:"ascore"`     // 客队得分

	// 网站A比赛球队
	Platform1Id           int     `json:"platform1Id" bson:"platform1Id"`
	Platform1AgentId      int64   `json:"platform1AgentId" bson:"platform1AgentId"`           // 下单账号
	Platform1GameId       int64   `json:"platform1GameId" bson:"platform1GameId"`             // 比赛ID
	Platform1GameDataId   int64   `json:"platform1GameDataId" bson:"platform1GameDataId"`     // 触发策略ID
	Platform1Handicap     float64 `json:"platform1Handicap" bson:"platform1Handicap"`         // 盘口, 最小值加0.25
	Platform1HandicapType int     `json:"platform1HandicapType" bson:"platform1HandicapType"` // 盘口类型 1 全场让球盘 2 全场大小盘 3 半场让球盘 4 半场大小盘
	Platform1FailReason   string  `json:"platform1FailReason" bson:"platform1FailReason"`     // 下单失败原因
	Platform1Rate         float64 `json:"platform1Rate" bson:"platform1Rate"`                 // 下单水位
	Platform1Price        int     `json:"platform1Price" bson:"platform1Price"`               // 下注金额
	PlayPlatform1RateTime int64   `json:"playPlatform1RateTime" bson:"playPlatform1RateTime"` // 下单时间
	Platform1Team         int     `json:"platform1Team" bson:"platform1Team"`                 // team 1 主场  2 客场
	Platform1Status       int     `json:"platform1Status" bson:"platform1Status"`             // 0 未下注  1 下注
	Platform1Result       string  `json:"platform1Result" bson:"platform1Result"`             // 下单结果 html

	// 网站B比赛球队
	Platform2Id            int     `json:"platform2Id" bson:"platform2Id"`
	Platform2AgentId       int64   `json:"platform2AgentId" bson:"platform2AgentId"`             // 下单账号
	Platform2GameId        int64   `json:"platform2GameId" bson:"platform2GameId"`               // 比赛ID
	Platform2GameDataId    int64   `json:"platform2GameDataId" bson:"platform2GameDataId"`       // 水位ID
	Platform2Team          int     `json:"platform2Team" bson:"platform2Team"`                   // team 1 主场  2 客场
	Platform2Rate          float64 `json:"platform2Rate" bson:"platform2Rate"`                   // 下单水位
	Platform2Price         int     `json:"platform2Price" bson:"platform2Price"`                 // 下注金额
	Platform2Handicap      float64 `json:"platform2Handicap" bson:"platform2Handicap"`           // 盘口, 最小值加0.25
	Platform2HandicapType  int     `json:"platform2HandicapType" bson:"platform2HandicapType"`   // 盘口类型 1 全场让球盘 2 全场大小盘 3 半场让球盘 4 半场大小盘
	Platform2FailReason    string  `json:"platform2FailReason" bson:"platform2FailReason"`       // 下单失败原因
	PlayPlatform2RateTime  int64   `json:"playPlatform2RateTime" bson:"playPlatform2RateTime"`   // 下单时间
	Platform2GameDataId2   int64   `json:"platform2GameDataId2" bson:"platform2GameDataId2"`     // 补单
	Platform2Rate2         float64 `json:"platform2Rate2" bson:"platform2Rate2"`                 // 水位
	Platform2Price2        int     `json:"platform2Price2" bson:"platform2Price2"`               // 补单金额
	Platform2FailReason2   string  `json:"platform2FailReason2" bson:"platform2FailReason2"`     // 补单失败原因
	PlayPlatform2Rate2Time int64   `json:"playPlatform2Rate2Time" bson:"playPlatform2Rate2Time"` // 补单时间
	Platform2Status        int     `json:"platform2Status" bson:"platform2Status"`               // 0 未下注  1 下注
	Platform2Result        string  `json:"platform2Result" bson:"platform2Result"`               // 下单结果 html
	TryTimes               int     `json:"tryTimes" bson:"tryTimes"`                             // 补单次数
	CreateTime             int64   `json:"createTime" bson:"createTime"`
}

type OrderData struct {
	Order             *Order    `json:"order" bson:"order"`                         //订单信息
	Policy            *Policy   `json:"policy" bson:"policy"`                       //下注策略
	Agent1            *Agent    `json:"agent1" bson:"agent1"`                       //下注账号1
	Platform1Id       int       `json:"platform1Id" bson:"platform1Id"`             //平台ID
	Platform1GameInfo *Game     `json:"platform1GameInfo" bson:"platform1GameInfo"` //赛事信息
	Platform1GameData *GameData `json:"platform1GameData" bson:"platform1GameData"` //赛事数据

	Agent2             *Agent    `json:"agent2" bson:"agent2"`                         //下注账号1
	Platform2Id        int       `json:"platform2Id" bson:"platform2Id"`               //平台ID
	Platform2GameInfo  *Game     `json:"platform2GameInfo" bson:"platform2GameInfo"`   //赛事信息
	Platform2GameData  *GameData `json:"platform2GameData" bson:"platform2GameData"`   //赛事数据
	Platform2GameData2 *GameData `json:"platform2GameData2" bson:"platform2GameData2"` //补单数据
	PageCount          int       `json:"pageCount" bson:"pageCount"`                   // 总页数
}

func (o *Order) UpdatePlatform1Status(price int, agentId int64) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	o.Platform1Status = 1
	o.PlayPlatform1RateTime = utils.CurrentMills()
	o.Platform1AgentId = agentId
	o.Platform1Price = price
	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{"$set": bson.M{
		"platform1Status":       o.Platform1Status,
		"playPlatform1RateTime": o.PlayPlatform1RateTime,
		"platform1AgentId":      o.Platform1AgentId,
		"platform1Price":        o.Platform1Price,
	}})
}

func (o *Order) UpdatePlatform1PlayFail(reason string) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"playPlatform1RateTime": utils.CurrentMills(),
			"platform1FailReason":   reason,
		},
	})
}

// 平台2首次下单失败时间更新
func (o *Order) UpdatePlatform2PlayFail(reason string) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"playPlatform2RateTime": utils.CurrentMills(),
			"platform2FailReason":   reason,
		},
	})
}

// 补单失败原因
func (o *Order) UpdatePlatform2PlayFail2(reason string) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"playPlatform2Rate2Time": utils.CurrentMills(),
			"platform2FailReason2":   reason,
		},
	})
}

// 下单水位
func (o *Order) UpdatePlatform2Status(agentId int64, rate float64, price int, gameData *GameData) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	o.Platform2Status = 1
	o.Platform2AgentId = agentId
	o.Platform2GameDataId = gameData.Id
	o.Platform2Rate = rate
	o.Platform2Price = price
	o.PlayPlatform2Rate2Time = utils.CurrentMills()
	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"platform2Status":       o.Platform2Status,
			"platform2AgentId":      o.Platform2AgentId,
			"platform2GameDataId":   o.Platform2GameDataId,
			"Platform2Rate":         o.Platform2Rate,
			"playPlatform2RateTime": o.PlayPlatform2Rate2Time,
			"platform2Price":        o.Platform2Price,
		},
	})
}

// 补单
func (o *Order) UpdatePlatform2Status2(agentId int64, newRate float64, times int, price int, gameData *GameData) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	o.Platform2Status = 1
	o.Platform2AgentId = agentId
	o.Platform2GameDataId2 = gameData.Id
	o.Platform2Rate2 = newRate
	o.Platform2Price2 = price
	o.PlayPlatform2Rate2Time = utils.CurrentMills()
	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"platform2Status":        o.Platform2Status,
			"platform2AgentId":       o.Platform2AgentId,
			"platform2GameDataId2":   o.Platform2GameDataId2,
			"platform2Rate2":         o.Platform2Rate2,
			"platform2Price2":        o.Platform2Price2,
			"playPlatform2Rate2Time": o.PlayPlatform2Rate2Time,
			"tryTimes":               times,
		},
	})
}

func (o *Order) UpdatePlatform1Result(html string) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"platform1Result": html,
		},
	})
}

func (o *Order) UpdatePlatform2Result(html string) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(ORDER_COL_STR, o.Id, bson.M{
		"$set": bson.M{
			"platform2Result": html,
		},
	})
}

func SaveOrder(order *Order) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	order.Id = int64(sess.AutoIncId(ORDER_COL_STR))
	return sess.Insert(ORDER_COL_STR, order)
}

func GetOrderList4UpResult(userId int64, inTime time.Duration) (list []*Order, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	query := bson.M{
		"userId":     userId,
		"$or":        []bson.M{bson.M{"platform1Status": 1}, bson.M{"platform2Status": 1}},
		"createTime": bson.M{"$gt": utils.CurrentMills() - int64(inTime/time.Millisecond)},
	}

	list = make([]*Order, 0, 100)
	err = sess.WithC(ORDER_COL_STR, func(col *mgo.Collection) error {
		return col.Find(query).Select(bson.M{
			"platform1Id":      1,
			"platform2Id":      1,
			"platform1AgentId": 1,
			"platform2AgentId": 1,
			"platform1Status":  1,
			"platform2Status":  1,
		}).All(&list)
	})
	return
}

func GetOrderList(userId int64, page int, pagesize int, show string) (orderdata []*OrderData, err error) {

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	if pagesize <= 0 {
		pagesize = 35
	}
	if show == "" {
		show = "success"
	}
	sql := bson.M{
		"userId": userId,
	}

	if show == "success" {
		sql["$or"] = []bson.M{bson.M{"platform1Status": 1}, bson.M{"platform2Status": 1}}
	}

	var orderlist []*Order
	orderlist = make([]*Order, 0, 100)
	orderdata = make([]*OrderData, 0)

	//取第几页数据，每页多少条  每页35条数据
	//"$or":    []bson.M{bson.M{"platform1Status": 1}, bson.M{"platform2Status": 1}},
	count := page * pagesize

	err = sess.WithC(ORDER_COL_STR, func(col *mgo.Collection) error {
		return col.Find(sql).Sort("-_id").Skip(count).Limit(pagesize).Select(bson.M{
			"_id":                    1,
			"userId":                 1,
			"hscore":                 1,
			"ascore":                 1,
			"policyId":               1,
			"platform1Id":            1,
			"platform1AgentId":       1,
			"platform1Status":        1,
			"platform1GameId":        1,
			"platform1GameDataId":    1,
			"platform1Handicap":      1,
			"platform1HandicapType":  1,
			"platform1FailReason":    1,
			"platform1Rate":          1,
			"platform1Price":         1,
			"playPlatform1RateTime":  1,
			"platform1Team":          1,
			"platform2Id":            1,
			"platform2AgentId":       1,
			"platform2Status":        1,
			"platform2GameId":        1,
			"platform2GameDataId":    1,
			"platform2Handicap":      1,
			"platform2HandicapType":  1,
			"platform2Rate":          1,
			"platform2Price":         1,
			"platform2FailReason":    1,
			"playPlatform2RateTime":  1,
			"platform2Team":          1,
			"platform2GameDataId2":   1,
			"platform2Rate2":         1,
			"platform2Price2":        1,
			"playPlatform2Rate2Time": 1,
			"tryTimes":               1,
			"createTime":             1,
		}).All(&orderlist)
	})

	//logs.Debug("GetOrderList===>", orderlist, page, err)
	if err != nil {
		return
	}

	pageCount := sess.Count(ORDER_COL_STR, sql)

	//orderdata = make([]*OrderData, 0)
	for _, order := range orderlist {
		data := new(OrderData)
		policy, err1 := GetpolicyById(order.PolicyId)
		//logs.Debug("GetOrderList", policy, err1, order.PolicyId)
		if err1 != nil {
			continue
		}
		data.Order = order
		data.Policy = policy
		data.Platform1Id = order.Platform1Id
		data.Platform2Id = order.Platform2Id
		data.PageCount = pageCount
		data.Platform1GameInfo, err1 = GetGameInfo(order.Platform1Id, order.Platform1GameId)
		if err1 != nil {
			continue
		}

		data.Platform1GameData, err1 = GetGameData(order.Platform1GameDataId)

		if err1 != nil {
			data.Platform1GameData = new(GameData)
		}

		data.Platform2GameInfo, err1 = GetGameInfo(order.Platform2Id, order.Platform2GameId)
		if err1 != nil {
			continue
		}

		data.Platform2GameData, err1 = GetGameData(order.Platform2GameDataId)
		//logs.Debug("Platform2GameData", data.Platform2GameData, err1)
		if err1 != nil {
			data.Platform2GameData = new(GameData)
		}

		if order.Platform2GameDataId2 != 0 {
			data.Platform2GameData2, err1 = GetGameData(order.Platform2GameDataId2)
			if err1 != nil {
				data.Platform2GameData2 = new(GameData)
			}
		}

		data.Agent1, err1 = GetAgentOne(order.Platform1AgentId)

		if err1 != nil {
			//continue
		}
		data.Agent2, err1 = GetAgentOne(order.Platform2AgentId)
		if err1 != nil {
			//continue
		}
		orderdata = append(orderdata, data)
	}

	return
}
func GetOrderResult(orderId int64) (order *Order, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	order = new(Order)

	err = sess.FindId(ORDER_COL_STR, orderId, order)
	return
}
